import { getCache, setCache, removeCache } from "../cacheUtils/cache";

// 使用常量集中管理缓存键名
export const USER_CACHE_KEYS = {
  ID: "id",
  NICKNAME: "nickName",
  AVATAR: "avatar",
  USER_TYPE: "userType",
  AGE: "age",
  GENDER: "gender",
  PHONE: "phone",
  ACCOUNT: "account",
  LAST_LOGIN_IP: "lastLoginIp",
  LAST_LOGIN_TIME: "lastLoginTime",
  IS_LOGGED_IN: "isLoggedIn",
  ALIPAY_QRCODE: "alipayQrCode",
  WX_QRCODE:'wxQrCode',
};

// 获取所有缓存键的数组
const USER_CACHE_KEY_ARRAY = Object.values(USER_CACHE_KEYS);

/**
 * 设置用户信息缓存
 * @param {Object} userInfo - 用户信息对象
 * @param {Object} [options] - 缓存选项
 * @param {number} [options.userInfoExpires] - 用户信息过期时间(ms)，默认2小时
 */
export const setUserCache = (userInfo, options = {}) => {
  Object.entries(userInfo).forEach(([key, value]) => {
    if (USER_CACHE_KEY_ARRAY.includes(key)) {
      setCache(key, value, options);
    }
  });
};

/**
 * 清除用户相关缓存
 * @returns {boolean} 是否全部清除成功
 */
export const clearUserCache = () => {
  let allSuccess = true;
  USER_CACHE_KEY_ARRAY.forEach((key) => {
    const success = removeCache(key);
    if (!success) {
      console.error(`Failed to remove cache for key: ${key}`);
      allSuccess = false;
    }
  });

  return allSuccess;
};

/**
 * 获取所有用户缓存信息
 * @returns {Object} 用户缓存信息对象
 */
export const getUserCache = () => {
  return USER_CACHE_KEY_ARRAY.reduce((cache, key) => {
    const value = getCache(key);
    if (value !== null) {
      try {
        // 尝试解析JSON格式的值
        cache[key] = JSON.parse(value);
      } catch {
        cache[key] = value;
      }
    }
    return cache;
  }, {});
};
